package ibase.solr.formatter;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

public class SearchFormatter 
{

	private static HashMap<String, String> objXslMap= new HashMap<String, String>();
	private static SearchFormatter searchFormatter= new SearchFormatter(); 
	
	private SearchFormatter()
	{
		
	}
	public static SearchFormatter getInstance()
	{
		return searchFormatter;
	}
	
	public static String getXSL(String objName)
	{
		String xslString ="";
		try 
		{
			if(objXslMap.containsKey(objName))
			{
			//	System.out.println("@@@@ In map xslString 1: [ "+objName+" ] : "+System.currentTimeMillis()+ " ]");
				xslString = objXslMap.get(objName);
				//System.out.println("@@@@ In map xslString");
			//	System.out.println("@@@@ In map xslString 2: [ "+objName+" ] : "+System.currentTimeMillis()+ " ]");
			}
			else
			{
			//	System.out.println("@@@@ not in map xslString 1: [ "+objName+" ] : "+System.currentTimeMillis()+ " ]");
				xslString = loadXSL(objName);
				//System.out.println("@@@@ not in map xslString");
		//		System.out.println("@@@@ not in map xslString 2: [ "+objName+" ] : "+System.currentTimeMillis()+ " ]");
			}
		} 
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return xslString;
	}
	
	private static String loadXSL(String objName) throws IOException
	{
		String xslPath = objName;
		String xslString = "";
		xslString = readFile(xslPath);
		objXslMap.put(objName,xslString);
		return xslString;
	}
	
	private static String readFile(String xslFilePath) throws IOException
	{
		String xslString ="";
		StringBuilder xslStringBuilder = new StringBuilder();;
		FileInputStream fStream = null;
		DataInputStream dInputStream = null;
		BufferedReader buffReader = null ;
		
		try 
		{
			File file = new File(xslFilePath);
			fStream = new FileInputStream(file);
			dInputStream = new DataInputStream(fStream);
			buffReader = new BufferedReader(	new InputStreamReader(dInputStream));
			
			while ((xslString = buffReader.readLine()) != null) 
			{
				xslStringBuilder.append(xslString);
			}
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		finally
		{
			if(fStream != null)
			{
				fStream.close();
			}
			if(dInputStream != null)
			{
				dInputStream.close();
			}
			if(buffReader != null)
			{
				buffReader.close();
			}
			
		}
		return xslStringBuilder.toString();
	}
}
